package com.skyjing.askitjava;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.res.TypedArray;
import android.util.DisplayMetrics;
import android.util.TypedValue;

import androidx.core.content.ContextCompat;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;

public class AsTool {
    private static Context mContext;

    public static void init(Context context) {
        mContext = context;
    }

    public static Context getApp() {
        return mContext;
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2dp(float pxValue) {
        float scale = mContext.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * dp转px
     *
     * @param dpVal
     * @return
     */
    public static int dp2px(float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, mContext.getResources().getDisplayMetrics());
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @return
     */
    public static int px2sp(float pxValue) {
        float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(float spValue) { //        float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
//        return (int) (spValue * fontScale + 0.5f);
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP,
                spValue, mContext.getResources().getDisplayMetrics()
        );
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static String getVersionName() {
        try {
            return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode() {
        try {
            return mContext.getPackageManager().getPackageInfo(
                    mContext.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
        }
        return 0;
    }

    /**
     * 获取屏幕宽度，px
     *
     * @return
     */
    public static float getScreenWidth() {
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度，px
     *
     * @return
     */
    public static float getScreenHeight() {
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     * 获取屏幕像素密度
     *
     * @return
     */
    public static float getDensity() {
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        return dm.density;
    }

    /**
     * 获取scaledDensity
     *
     * @return
     */
    public static float getScaledDensity() {
        DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
        return dm.scaledDensity;
    }

    /**
     * 获取颜色
     */
    public static int getColor(int id) {
        return ContextCompat.getColor(mContext, id);
    }

    public static String getPageName() {
        return mContext.getPackageName();
    }

    /**
     * 判断当前APP是否存活
     */
    public static boolean isAppAlive(Context context, String packageName) {
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processInfos = activityManager.getRunningAppProcesses();
        for (int i = 0; i < processInfos.size(); i++) {
            if (packageName.equals(processInfos.get(i).processName)) {
                return true;
            }
        }
        return false;
    }

//    private fun getAppSignatureHash(packageName: String, algorithm: String): String? {
//        if (isSpace(packageName)) return ""
//        val signature: Array<Signature> = getAppSignature(packageName)
//        return if (signature == null || signature.size <= 0) "" else bytes2HexString(
//            hashTemplate(
//                signature[0].toByteArray(), algorithm
//            )
//        )
//            .replaceAll("(?<=[0-9A-F]{2})[0-9A-F]{2}", ":$0")
//    }

    private static boolean isSpace(String s) {
        if (s == null) return true;
        int i = 0;
        int len = s.length();
        while (i < len) {
            if (!Character.isWhitespace(s.charAt(i))) {
                return false;
            }
            ++i;
        }
        return true;
    }

    public static Signature[] getAppSignature() {
         if (mContext != null) {
            getAppSignature(mContext.getPackageName());
        } else {
            return null;
        }
        return null;
    }

    /**
     * Return the application's signature.
     *
     * @param packageName The name of the package.
     * @return the application's signature
     */
    public static Signature[] getAppSignature(String packageName) {
         if (isSpace(packageName)){
             return null;
         } else {
             try {
                 PackageManager pm = getApp().getPackageManager();
                 @SuppressLint("PackageManagerGetSignatures")
                 PackageInfo pi = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
                 return pi.signatures;
             } catch (PackageManager.NameNotFoundException e) {
                 e.printStackTrace();
             }
         }
         return null;
    }
}
